package com.formssi.easyexcel.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.formssi.easyexcel.listener.UploadDataListener;
import com.formssi.easyexcel.listener.UploadExcelListener;
import com.formssi.easyexcel.mapper.UploadDAO;
import com.formssi.easyexcel.pojo.DownloadData;
import com.formssi.easyexcel.pojo.UploadData;
import com.formssi.easyexcel.pojo.UserExcel2;
import com.formssi.easyexcel.service.ExcelService;
import com.formssi.easyexcel.service.ExcelService2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.sql.Timestamp;
import java.util.*;

/**
 * web读写案例
 *
 * @author Jiaju Zhuang
 **/
@Controller
public class WebTest {

    @Autowired
    @Qualifier("excelServiceImpl")
    private ExcelService excelService;

    @Autowired
    @Qualifier("excelServiceImpl2")
    private ExcelService2 excelService2;

    @Resource
    private UploadDAO uploadDAO;

    @GetMapping("/findAllUser")
    @ResponseBody
    public List findAllUser1(){
        return excelService.findAllUser();
    }
    @GetMapping("/findAllUser2")
    @ResponseBody
    public List findAllUser2(){
        return excelService2.findAllUser();
    }

    /**
     * 文件下载（失败了会返回一个有部分数据的Excel）
     * <p>
     * 1. 创建excel对应的实体对象 参照{@link DownloadData}
     * <p>
     * 2. 设置返回的 参数
     * <p>
     * 3. 直接写，这里注意，finish的时候会自动关闭OutputStream,当然你外面再关闭流问题不大
     */
    @GetMapping("/download")
    public void download(HttpServletResponse response) throws IOException {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码
        String fileName = URLEncoder.encode("用户数据", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        long start = System.currentTimeMillis();
        EasyExcel.write(response.getOutputStream(), UserExcel2.class).sheet("用户信息").doWrite(getUsers2());
        System.out.println(System.currentTimeMillis()-start);//6614ms
    }

    /**
     * 文件下载并且失败的时候返回json（默认失败了会返回一个有部分数据的Excel）
     */
    @GetMapping("/downloadFailedUsingJson")
    public void downloadFailedUsingJson(HttpServletResponse response) throws IOException {
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("测试", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            // 这里需要设置不关闭流
            EasyExcel.write(response.getOutputStream(), DownloadData.class).autoCloseStream(Boolean.FALSE).sheet("模板")
                    .doWrite(data());
        } catch (Exception e) {
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, String> map = new HashMap<String, String>();
            map.put("status", "failure");
            map.put("message", "下载文件失败" + e.getMessage());
            response.getWriter().println(JSON.toJSONString(map));
        }
    }

    /**
     * 文件上传
     * <p>
     * 1. 创建excel对应的实体对象 参照{@link UploadData}
     * <p>
     * 2. 由于默认一行行的读取excel，所以需要创建excel一行一行的回调监听器，参照{@link UploadDataListener}
     * <p>
     * 3. 直接读即可
     */
    @RequestMapping("/upload")
    @ResponseBody
    public String upload(MultipartFile file) throws IOException {
//        System.out.println(file);
        long start = System.currentTimeMillis();
        EasyExcel.read(file.getInputStream(), UserExcel2.class, new UploadExcelListener(excelService)).sheet().doRead();
        System.out.println(System.currentTimeMillis()-start);
        return "success";
    }


    private List<DownloadData> data() {
        List<DownloadData> list = new ArrayList<DownloadData>();
        for (int i = 0; i < 10000; i++) {
            DownloadData data = new DownloadData();
            data.setString("字符串" + 0);
            data.setDate(new Date());
            data.setDoubleData(0.56);
            list.add(data);
        }
        return list;
    }

    public static List<UserExcel2> getUsers2() {
        List<UserExcel2> userExcelList = new ArrayList<UserExcel2>();
        for (int i = 0; i < 10; i++) {
            UserExcel2 userExcel2 = new UserExcel2();
            userExcel2.setId(i);
            userExcel2.setName("小明" + i);
            userExcel2.setAge(18);
            userExcel2.setPhone("13713816676");
            if (i % 2 == 0) userExcel2.setSex("男");
            else userExcel2.setSex("女");
            userExcel2.setBirthday(new Timestamp(new Date().getTime()));
            userExcel2.setAddress("人民南路" + i + "号");
            userExcel2.setEmail("1971587947@qq.com");
            userExcel2.setCollege("深圳大学");
            userExcel2.setMajor(i % 2 == 0 ? "计算机科学与技术" : "软件工程");
            userExcel2.setInstData(new Timestamp(new Date().getTime()));
            userExcel2.setModiTime(new Timestamp(new Date().getTime()));
            userExcelList.add(userExcel2);
        }
        return userExcelList;
    }
}
